package org.apache.ibatis.common.reflection.wrapper;

import org.apache.ibatis.common.reflection.*;
import org.apache.ibatis.common.reflection.factory.ObjectFactory;
import org.apache.ibatis.common.reflection.invoker.Invoker;
import org.apache.ibatis.common.reflection.property.PropertyTokenizer;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @Name BeanWrapper
 * @Description: Bean 对象包装器 [实现] 类
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-28 16:05:59
 **/
public class BeanWrapper extends BaseWrapper {
    // 被包装的对象
    private final Object object;
    // 被包装对象所属类的 “元” 类
    private final MetaClass metaClass;

    public BeanWrapper(MetaObject metaObject, Object object) {
        super(metaObject);
        this.object = object;
        this.metaClass = MetaClass.forClass(object.getClass(), metaObject.getReflectorFactory());
    }

    @Override
    public Object get(PropertyTokenizer prop) {
        if (prop.getIndex() != null) {
            // 不是单一属性，而是有数组
            Object collection = resolveCollection(prop, object);
            return getCollectionValue(prop, collection);
        } else return getBeanProperty(prop, object);
    }

    /**
     * 通过调用 getter 方法获取 Bean 属性
     *
     * @param prop   属性标记器（属性名称）
     * @param object 目标对象
     * @return java.lang.Object 结果
     * @version v1.0.0
     * @author lichao
     * @date 2024-04-28 16:10:29
     */
    private Object getBeanProperty(PropertyTokenizer prop, Object object) {
        try {
            Invoker method = metaClass.getGetInvoker(prop.getName());
            try {
                return method.invoke(object, NO_ARGUMENTS);
            } catch (Throwable e) {
                throw ExceptionUtil.unwrapThrowable(e);
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            String errorMsg = "无法从目标类 [" + object.getClass() + "] 中获取属性 <" + prop.getName() + ">，原因是：" + e.toString();
            throw new ReflectorException(errorMsg, e);
        }
    }

    @Override
    public void set(PropertyTokenizer prop, Object value) {
        if (prop.getIndex() != null) {
            Object collection = resolveCollection(prop, object);
            setCollectionValue(prop, collection, value);
        } else setBeanProperty(prop, object, value);
    }

    private void setBeanProperty(PropertyTokenizer prop, Object object, Object value) {
        try {
            Invoker method = metaClass.getSetInvoker(prop.getName());
            Object[] params = {value};
            try {
                method.invoke(object, params);
            } catch (Throwable e) {
                throw ExceptionUtil.unwrapThrowable(e);
            }
        } catch (Throwable e) {
            String errorMsg = "无法向目标类 [" + object.getClass() + "] 中设置属性 <" + prop.getName() + "> 的值，原因是：" + e.toString();
            throw new ReflectorException(errorMsg, e);
        }
    }

    @Override
    public String findProperty(String name, boolean useCamelCaseMapping) {
        return metaClass.findProperty(name, useCamelCaseMapping);
    }

    @Override
    public String[] getGetterNames() {
        return metaClass.getGetterNames();
    }

    @Override
    public String[] getSetterNames() {
        return metaClass.getSetterNames();
    }

    @Override
    public Class<?> getGetterType(String name) {
        PropertyTokenizer prop = new PropertyTokenizer(name);
        if (prop.hasNext()) {
            MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
            if (metaValue == SystemMetaObject.NULL_META_OBJECT)
                return metaClass.getGetterType(name);
            else
                return metaValue.getGetterType(prop.getChildren());
        } else return metaClass.getGetterType(name);
    }

    @Override
    public Class<?> getSetterType(String name) {
        PropertyTokenizer prop = new PropertyTokenizer(name);
        if (prop.hasNext()) {
            MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
            if (metaValue == SystemMetaObject.NULL_META_OBJECT)
                return metaClass.getSetterType(name);
            else
                return metaValue.getSetterType(name);
        } else return metaClass.getGetterType(name);
    }

    @Override
    public boolean hasSetter(String name) {
        PropertyTokenizer prop = new PropertyTokenizer(name);
        if (prop.hasNext()) {
            if (metaClass.hasSetter(prop.getIndexedName())) {
                MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
                if (metaValue == SystemMetaObject.NULL_META_OBJECT)
                    return metaClass.hasSetter(name);
                else
                    return metaValue.hasSetter(prop.getChildren());
            } else return false;
        } else return metaClass.hasSetter(name);
    }

    @Override
    public boolean hasGetter(String name) {
        PropertyTokenizer prop = new PropertyTokenizer(name);
        if (prop.hasNext()) {
            if (metaClass.hasGetter(prop.getIndexedName())) {
                MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
                if (metaValue == SystemMetaObject.NULL_META_OBJECT)
                    return metaClass.hasGetter(name);
                else
                    return metaValue.hasGetter(prop.getChildren());
            } else return false;
        } else return metaClass.hasGetter(name);
    }

    @Override
    public MetaObject instantiatePropertyValue(String name, PropertyTokenizer prop, ObjectFactory objectFactory) {
        MetaObject metaValue;
        Class<?> type = getSetterType(prop.getName());
        try {
            Object newObject = objectFactory.create(type);
            metaValue = MetaObject.forObject(newObject, metaObject.getObjectFactory(), metaObject.getObjectWrapperFactory(), metaObject.getReflectorFactory());
            set(prop, newObject);
        } catch (Exception e) {
            String errorMsg = "无法为属性 <" + name + "> 设置值，因为属性 <" + name + "> 为 null，且不能被类 [" + type.getName() + "] 实例化，原因为：" + e.toString();
            throw new ReflectorException(errorMsg, e);
        }
        return metaValue;
    }

    @Override
    public boolean isCollection() {
        return false;
    }

    @Override
    public void add(Object element) {
        throw new UnsupportedOperationException();
    }

    @Override
    public <E> void addAll(List<E> element) {
        throw new UnsupportedOperationException();
    }
}

